<script setup>
import EditContainer from "@/components/AdminConponents/EditContainer.vue";
import {onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {gameEditAPI, gameGetAPI} from "@/api/AdminApi/game.js";
import {formatToLocalDate} from "@/utils/format.js";
import 'element-plus/theme-chalk/el-message.css'
import {ElMessage} from "element-plus";

const route = useRoute()
const gameInfo = ref({
  id: null,
  chineseName: null,
  englishName: null,
  issueDate: null,
  developer: null
})
const gameName = ref()

const getGameInfo = async (id = route.params.id) => {
  const res = await gameGetAPI(id)
  /* eslint-disable no-unused-vars */
  const gameData = res.data
  gameInfo.value.id = gameData.id
  gameInfo.value.chineseName = gameData.chineseName
  gameInfo.value.englishName = gameData.englishName
  gameInfo.value.issueDate = gameData.issueDate
  gameInfo.value.developer = gameData.developer
  gameName.value = gameData.chineseName
}
onMounted(() => getGameInfo())

// 取消按钮
const router = useRouter()
const cancel = () => {
  router.go(-1)
}

const rules = {
  chineseName: [
    { required: true, message: '请输入中文名', trigger: 'blur' }
  ],
  englishName: [
    { required: true, message: '请输入英文名', trigger: 'blur' }
  ],
  issueDate: [
    { required: true, message: '请输入发行日期', trigger: 'blur' }
  ],
  developer: [
    { required: true, message: '请输入发行商', trigger: 'blur' }
  ]
}

const formRef = ref()
// 修改按钮
const edit = async () => {
  await formRef.value.validate()
  gameInfo.value.issueDate = formatToLocalDate(gameInfo.value.issueDate)
  const res = await gameEditAPI(gameInfo.value)
  if (res.code === 1) {
    ElMessage.success("更新成功")
    router.go(-1)
  } else {
    ElMessage.error(res.msg)
  }
}
</script>

<template>
  <EditContainer :title="`${gameName}游戏基本信息编辑`">
    <template #body>
      <el-form ref="formRef" :model="gameInfo" :rules="rules" label-width="auto" style="max-width: 1200px">
        <el-form-item label="游戏中文名称" prop="chineseName">
          <el-input v-model="gameInfo.chineseName"></el-input>
        </el-form-item>
        <el-form-item label="游戏英文名称" prop="englishName">
          <el-input v-model="gameInfo.englishName"></el-input>
        </el-form-item>
        <el-form-item label="发行日期" prop="issueDate">
          <el-date-picker
              v-model="gameInfo.issueDate"
              type="date"
              placeholder="请选择创建日期"
          />
        </el-form-item>
        <el-form-item label="开发商" prop="developer">
          <el-input v-model="gameInfo.developer"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footerLeft>
      <el-button class="button" @click="cancel" type="info">取消</el-button>
    </template>
    <template #footerRight>
      <el-button class="button" @click="edit" type="primary">修改</el-button>
    </template>
  </EditContainer>
</template>

<style scoped>

</style>
